<?php
    class Page extends CI_Controller {

    public $language;
    public $lan;

    function Page() {
        parent::__construct();
	$this->load->model('download_model');
	$this->load->model('app_model');
    }
    
    function index(){
        
    }
    function download($code=''){
	/*
	 * download function with code
	 * after download finish the code will be expired
	 */
	$this->db->escape_str($code);
	$this->db->where('code',$code);
	$query = $this->db->get('download');
	if ($query->num_rows>0)
		$query = $query->first_row();
	else die();
	if ($query->status==1)die('Your download has been expired');
	$this->db->where('id',$query->template_id);
	$temp = $this->db->get('app');
	if ($temp->num_rows>0)
		$temp = $temp->first_row();
	else die();
	$system_path = $temp->path;
	$ex= explode('/', $system_path);

	$fsize = filesize($system_path);
	$name = $ex[1];
	header("Content-Type: xap");
	header('Content-Disposition: attachment; filename='.$name);
	header("Content-Transfer-Encoding: binary");
	header("Content-Length: ".$fsize );
	$download_rate = 500;
	flush();
	$file = fopen($system_path,"r");

	if ($file) {
	  while(!feof($file)) {
		print(fread($file, 1024*8));
		flush();

		if (connection_status()!=0) {
		fclose($file);
		}
	  }
	$d = array('downloadstatus'=>1);
	$this->db->where('id',$id);
	$this->db->update('payment',$d);
	$this->db->where('id',$temp->id);
	$this->db->update('app',array('download'=>$temp->download+1));
	}


	fclose($file);
	 
    }
    function get_app($id){
	//$data['user_id'] = $this->session->get_userdata('user_id');
	if ($this->app_model->check_available($id)){
	    $data['app_id'] = $id;
	}
	else
	{
	    echo ('You have no permission to download this file');
	}
	$dl = $this->download->add($data);
	if ($dl){
	    redirect(base_url().'/download/'.$dl->code);
	}
	else
	{
	    echo('Internal Server Error');
	}
	
    }
}

?>